const net = require('net');
module.exports = async function (mailConfig) {
    try{
        const host = mailConfig.host,
            port = mailConfig.port || 25,
            user = mailConfig.user,
            pass = mailConfig.pass,
            to = mailConfig.to || [],
            subject = new Buffer(mailConfig.subject).toString('base64'),
            mailBody = mailConfig.mailBody;

        let client = net.createConnection({host,port},async() => {
            // 连接成功
            let code
            code = await getData()

            // 发送EHLO 交互信号
            sendData('EHLO ' + host)
            code = await getData()

            // 发送登陆信号 AUTH LOGIN
            sendData('AUTH LOGIN')
            code = await getData()

            // 发送用户名（邮箱），进行base64编码
            sendData(new Buffer(user).toString('base64'))
            code = await getData()

            // 发送密码，进行base64编码
            sendData(new Buffer(pass).toString('base64'))
            code = await getData()

            // 设置发送人
            sendData(`MAIL FROM:<${user}>`)
            code = await getData()

            // 设置收件人
            for(var i=0; i<to.length; i++){
                sendData(`RCPT TO:<${to[i]}>`)
            }
            code = await getData()

            // 发送邮件内容信号：DATA
            sendData('DATA')
            code = await getData()

            // 发主题
            sendData(`SUBJECT: =?utf-8?B?${subject}?=`)
            // 发发件人
            sendData(`FROM:${user}`)

            //设置邮件格式
            sendData(`MIME-Version: 1.0`)
            sendData(`Content-Type: text/html;charset=utf-8`)
            sendData(`Content-Transfer-Encoding: 8bit\r\n`)

            //开始发送邮件内容
            sendData(`${mailBody}\r\n.`)
            code = await getData()

            //发送断开信号
            sendData(`QUIT`)

        })

        function getData() {
            return new Promise((resolve,reject) => {
                next()
                function next(){
                    if(data) {
                        let temp = data
                        data =null
                        resolve(temp)
                    } else {
                        setTimeout(next,0)
                    }
                }
            })
        }

        function sendData(msg) {
            client.write(msg+'\r\n')
        }

        let data = null
        client.on('data', d => {
            data = d.toString().substring(0,3)
        })
        client.on('end', () => {
        })
    }catch(e){
        console.log(e.stack)
    }
}